#include <thread>

#include "aip-cpp-sdk/speech.h"
#include "channel.hpp"
#include "etcd.hpp"
#include "speech.pb.h"


DEFINE_bool(debug, true, "是否为调试模式");
DEFINE_string(logPath, "", "日志路径");
DEFINE_int32(logLevel, 0, "日志等级");

DEFINE_string(etcdHost, "http://127.0.0.1:2379", "etcd的IP地址");
DEFINE_string(baseService, "/service", "服务监控根目录");
DEFINE_string(speechService, "/service/speech", "服务信道目录");



int main(int argc, char* argv[])
{
    google::ParseCommandLineFlags(&argc, &argv, true);

    im::initLogger(FLAGS_debug, FLAGS_logPath, FLAGS_logLevel);

    // 1.先构建RPC信道管理对象
    auto sm = std::make_shared<im::ServiceManager>();
    sm->declared(FLAGS_speechService);
    auto put_cb = std::bind(&im::ServiceManager::onServiceOnline, sm.get(), std::placeholders::_1, std::placeholders::_2);
    auto del_cb = std::bind(&im::ServiceManager::onServiceOffline, sm.get(), std::placeholders::_1, std::placeholders::_2);

    //2. 构造服务发现对象
    // im::Discover discover(FLAGS_etcdHost, FLAGS_baseService, put_cb, del_cb);
    im::Discover::ptr discover = std::make_shared<im::Discover>(FLAGS_etcdHost, FLAGS_baseService, put_cb, del_cb);

    //3. 通过rpc信道管理对象，获取提供speech服务rpc服务的信道
    auto channel = sm->choose(FLAGS_speechService);
    if(channel == nullptr){
        im::LOG_CRITICAL("获取信道失败");
        return -1;
    }

    //4. 发起speech服务的Rpc调用
    im::SpeechService_Stub stub(channel.get());
    brpc::Controller* cntl = new brpc::Controller();
    cntl->set_timeout_ms(1000);
    cntl->set_max_retry(3);

    std::string file_content;
    aip::get_file_content("../test/sound.pcm", &file_content);  // 这里是以CMakeLists.txt所在的路径为根路径
    im::LOG_DEBUG("语音文件长度：{}", file_content.size());

    im::SpeechRecognitionReq req;
    req.set_speech_content(file_content);
    req.set_request_id("1111");

    im::SpeechRecognitionRsp* rsp = new im::SpeechRecognitionRsp();
    stub.SpeechRecognition(cntl, &req, rsp, nullptr);
    
    if(cntl->Failed() == true){
        im::LOG_CRITICAL("Rpc调用失败：{}", cntl->ErrorText());
        delete cntl;
        delete rsp;
        return -1;
    }
    if (rsp->success() == false) {
        im::LOG_CRITICAL("响应错误：{}", rsp->errmsg());
        return -1;
    }
    im::LOG_INFO("收到响应: id={}, 内容：{}", rsp->request_id(), rsp->recognition_result());   
    return 0;
}